package com.zz.service.impl;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.qiniu.storage.model.DefaultPutRet;
import com.zz.common.R;
import com.zz.entity.Activity;
import com.zz.entity.Club;
import com.zz.entity.User;
import com.zz.mapper.ActivityMapper;
import com.zz.mapper.ClubMapper;
import com.zz.mapper.UserMapper;
import com.zz.service.ClubService;
import com.zz.service.QiniuService;
import com.zz.utils.AesEncryptUtils;
import com.zz.utils.QiniuUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.InputStream;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * @author HUAWEI
 */
@Service
@Slf4j
public class QiniuServiceImpl implements QiniuService {

    @Autowired
    private QiniuUtil qiniuUtil;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private ClubMapper clubMapper;

    @Autowired
    private ActivityMapper activityMapper;

    @Value("${qiniu.fileDomain}")
    private String fileDomain;

    @Override
    public R upload(MultipartFile file) {
        if (file.isEmpty()) {
            return R.error("上传文件不能为空");
        }
        try {
            InputStream fileInputStream =  file.getInputStream();
            String originalFilename = file.getOriginalFilename();
            String fileExtend = originalFilename.substring(originalFilename.lastIndexOf("."));
            String yyyyMMddHHmmss = DateUtil.format(new Date(), "yyyyMMddHHmmss");
            //默认不指定key的情况下，以文件内容的hash值作为文件名
            String fileKey = UUID.randomUUID().toString().replace("-", "") + "-" + yyyyMMddHHmmss + fileExtend;
            Map<String, Object> map = new HashMap<>();
            DefaultPutRet uploadInfo = qiniuUtil.upload(fileInputStream, fileKey);
            map.put("fileName", uploadInfo.key);
            map.put("originName", originalFilename);
            map.put("size", file.getSize());
            log.info("文件：" + JSON.toJSONString(map));
            return R.success(map).add("fileName",uploadInfo.key);
        } catch (Exception e) {
            e.printStackTrace();
            return R.error("上传失败");
        }
    }

    @Override
    public R<String> uploadUser(MultipartFile file, HttpServletRequest request) {
        R upload = upload(file);
        Map map = upload.getMap();
        String fileName = (String) map.get("fileName");

        // 获取用户信息
        String userName = (String) request.getSession().getAttribute("user");

        LambdaQueryWrapper<User> userWrapper = new LambdaQueryWrapper<>();
        userWrapper.eq(User::getName, userName);
        User user = userMapper.selectOne(userWrapper);

        user.setAvatar(AesEncryptUtils.encrypt(fileName));

        userMapper.updateById(user);

        return R.success("成功上传用户头像");
    }

    @Override
    public R<String> uploadClub(int clubId, MultipartFile file) {
        // 获取社团信息
        Club club = clubMapper.selectById(clubId);

        R upload = upload(file);
        Map map = upload.getMap();
        String fileName = (String) map.get("fileName");

        club.setImage(AesEncryptUtils.encrypt(fileName));
        clubMapper.updateById(club);

        return R.success("成功上传社团图片！");
    }

    @Override
    public R<String> uploadActivity(int activityId, MultipartFile file) {
        R upload = upload(file);
        Map map = upload.getMap();
        String fileName = (String) map.get("fileName");

        // 获取活动信息
        Activity activity = activityMapper.selectById(activityId);
        activity.setImage(AesEncryptUtils.encrypt(fileName));
        activityMapper.updateById(activity);

        return R.success("成功上传活动图片！");
    }

    @Override
    public R<String> getClubUrl(int clubId) {
        Club club = clubMapper.selectById(clubId);
        String image = club.getImage();
        //解密
        image = AesEncryptUtils.decrypt(image);

        return R.success(fileDomain+"/"+image);
    }

    @Override
    public R<String> getUserUrl(int userId) {
        User user = userMapper.selectById(userId);
        String avatar = user.getAvatar();
        //解密
        avatar = AesEncryptUtils.decrypt(avatar);
        return R.success(fileDomain+"/"+avatar);
    }

    @Override
    public R<String> getActivityUrl(int activityId) {
        Activity activity = activityMapper.selectById(activityId);
        String image = activity.getImage();
        //解密
        image = AesEncryptUtils.decrypt(image);

        return R.success(fileDomain+"/"+image);
    }
}
